import React, { forwardRef, useCallback, useImperativeHandle, useState } from 'react'
import { Form, Input, DatePicker, } from 'antd'
import { getMessage } from '@inbiz/react';
import { useDebounceFunc } from '@inbiz/hooks';
import FormItemTitle from '../components/FormItemTitle'
import MultiplePanel from './MultiplePanel'
import CategoryRender from './CategoryRender'
import { getPageSearchData } from '../../../../../../SearchEngine/preview/web/components/SmallPanelView/SmallPanelAdvancedSearch/utils'
import './index.less'

function PanelArea(props, ref) {
  const { list, selected, onSelected, config, $categoryData, categoryLevel } = props

  const [form] = Form.useForm();
  const [isCustom, $isCustom] = useState<any>([])
  const resetItem = useCallback((index) => {
    list.slice(index).forEach(item => {
      form.resetFields([item.Key])
    })
  }, [list])
  const clearField = (index) => {
    resetItem(index);
    categoryLevel.current = index;
    $categoryData(categoryData => {
      const newData = { ...categoryData };
      Object.keys(newData).map(item => Number(item.split('_')[1])).forEach(level => {
        if (level >= index) {
          delete newData['level_' + level];
        }
      })
      return newData
    })
    // 清空的时候,自定义也要取消选中
    $isCustom(oldCustom => {
      const newCustom = [...oldCustom]
      const i = newCustom.findIndex(ele => ele.level == index)
      if (i > -1) {
        newCustom.splice(i, 1)
      }
      return newCustom
    })
  }
  // 当有特殊符号时,不发送请求,验证通过后再发
  // 当有特殊符号时,不发送请求,验证通过后再发
  const onValuesChange = useDebounceFunc((sort, changedValues) => {
    form.validateFields().then(res => {
      if (res) {
        categoryLevel.current = sort;
        $categoryData(categoryData => {
          const newData = { ...categoryData }
          const formatVal = getPageSearchData(changedValues)
          newData[`level_${sort}`] = [formatVal]
          return newData
        })
      }
    })
  }, 500)
  const getComponent = (key: string, sort, name) => {
    if (key == 'date') {
      return <DatePicker.RangePicker showTime={false} onChange={(val) => {
        onValuesChange(sort, { [name]: val })
      }} />
    }
    return <Input placeholder={getMessage('SearchResultEngine.pleaseInput')} onChange={(e) => {
      onValuesChange(sort, { [name]: e.target.value })
    }} />
  }

  useImperativeHandle(ref, () => {
    return {
      resetAll: () => {
        form.resetFields()
        $isCustom([])
      }
    }
  })
  // 筛选所选的自定义切面是否存在
  const fiterCustom = (val) => {
    return isCustom.some(item => item.value == val)
  }
  const setCutomValue = (parentItem: any, level: number, type?: string) => {
    const hasValue = fiterCustom(parentItem.Value)
    if (type == '1') {
      const newIsCustom = isCustom.filter(item => item.level <= level)
      const customIndex = newIsCustom.findIndex(item => item.value == parentItem.Value)
      if (customIndex > -1) {
        newIsCustom.splice(customIndex, 1)
        $isCustom(newIsCustom)
      }
      return
    }
    if (!hasValue) {
      $isCustom([...isCustom, { value: parentItem.Value, level }])
    }
  }

  return (
    <div className='panelArea'>
      {/* <div>切面</div> ShowHierarchy == 1时, 不显示第一级, 但level值得一样, 就不能处理数据*/}
      <Form onSubmitCapture={(e) => { e.preventDefault(); return false }} form={form} >
        {
          list.map((item, index) => {
            // 这是二级和三级标题 
            if (item.ShowHierarchy == 1 && item.IsGroup) {
              return <div key={item.Value}>
                {
                  item.SectionGroupData.map(ele => {
                    return ele.sectionItemList?.length > 0 && <>
                      <FormItemTitle config={config} title={ele.Value} clearField={() => clearField(index)} showClear={selected.some(ele => ele.includes(item.Key))} />
                      <CategoryRender
                        item={ele}
                        parentItem={item}
                        selected={selected}
                        onSelected={onSelected}
                        level={index}
                        IsWhether={item?.IsWhether}
                        config={config}
                        isCustom={isCustom}
                        setCutomValue={setCutomValue}
                        fiterCustom={fiterCustom}
                        needSlice
                        resetItem={() => resetItem(index)}
                      />
                    </>

                  })
                }
                {item.IsCustomSearch && isCustom.includes(item.Value) &&
                  <Form.Item name={item.Key} >
                    {getComponent(item.IndexFieldType, index, item.Key)}
                  </Form.Item>
                }
              </div>
            }
            // 当没有切面的时候,title也不出现, sectionItemList是切面, SectionGroupData是分组--切面
            return (item.sectionItemList?.length > 0 || item.SectionGroupData?.length > 0) && <div key={item.Value}>
              <FormItemTitle config={config} title={item.Value} clearField={() => clearField(index)} showClear={selected.some(ele => ele.includes(item.Key))} />
              {item.ShowHierarchy !== 1 && item.IsGroup ?
                <MultiplePanel
                  {...item}
                  level={index}
                  parentItem={item}
                  config={config}
                  selected={selected}
                  onSelected={onSelected}
                  form={form}
                  isCustom={isCustom}
                  setCutomValue={setCutomValue}
                  fiterCustom={fiterCustom}
                  resetItem={() => resetItem(index)}
                /> :
                <CategoryRender
                  item={item}
                  parentItem={item}
                  selected={selected}
                  onSelected={onSelected}
                  level={index}
                  IsWhether={item?.IsWhether}
                  config={config}
                  needSlice
                  resetItem={() => resetItem(index)}
                  setCutomValue={setCutomValue}
                  fiterCustom={fiterCustom}
                  isCustom={isCustom}

                />
              }
              {item.IsCustomSearch && fiterCustom(item.Value) > 0 &&
                <Form.Item name={item.Key}
                  rules={[
                    () => ({
                      validator(_, value) {
                        if (item.Key == 'fileextname') {
                          const regStr = /[!~^()\-\+{}\[\]\\:"\/]/g // 这几个符号是一个一个输进去试出来的
                          if (regStr.test(value)) {
                            return Promise.reject(new Error(getMessage('SearchResultEngine.specialsymbol')))
                          }
                        }
                      },
                    })
                  ]
                  }>
                  {getComponent(item.IndexFieldType, index, item.Key)}
                </Form.Item>
              }
            </div>
          })
        }
      </Form>
    </div>
  )
}
export default forwardRef(PanelArea)
